package com.leantech.android.browser.ui.shortcut.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cscj.android.repository.db.entity.BrowseHistoryEntity
import com.cscj.android.repository.db.entity.FavoritesEntity
import com.cscj.android.repository.db.entity.ShortCutEntryEntity
import com.cscj.android.repository.network.Result
import com.cscj.android.repository.repo.favorites.FavoritesRepository
import com.cscj.android.repository.repo.history.BrowserHistoryRepository
import com.cscj.android.repository.repo.shortcut.ShortCutRepository
import com.leantech.android.browser.ui.shortcut.adapter.CommentShortCut
import com.cscj.android.utils.LOG
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class ShortCutViewModel : ViewModel(), KoinComponent {

    private val shortCutRepository by inject<ShortCutRepository>()

    private val historyRepository by inject<BrowserHistoryRepository>()

    private val favoritesRepository by inject<FavoritesRepository>()

    val linkShortCutFlow = shortCutRepository.loadShortCuts().stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = Result.Loading()
    )

    private val _historyRefreshTrigger = MutableStateFlow(0)

    val historyFlow = _historyRefreshTrigger.flatMapLatest {
        historyRepository.allBrowserHistory()
    }.map { histories ->
        histories.distinctBy {
            it.url
        }.map { history ->
            CommentShortCut.HistoryShortCut(
                history, shortCutRepository.isItemAdded(
                    ShortCutEntryEntity.EntryTypeHistory,
                    if (history.isRootItem()) null else history.url
                )
            )
        }
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    )

    private val _favoritesRefreshTrigger = MutableStateFlow(0)

    val favoritesFlow = _favoritesRefreshTrigger.flatMapLatest {
        favoritesRepository.allFavorites()
    }.map { favorites ->
        favorites.map { f ->
            val itemAdded = shortCutRepository.isItemAdded(
                ShortCutEntryEntity.EntryTypeFavorites,
                if (f.type == FavoritesEntity.TYPE_ROOT) null else f.url
            )
            LOG.d("Favorites item $f , itemAdded $itemAdded")
            CommentShortCut.FavoriteShortCut(
                f, itemAdded
            )
        }
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    )

    fun refreshFavorites() {
        _favoritesRefreshTrigger.update { it + 1 }
    }

    fun refreshHistory() {
        _historyRefreshTrigger.update { it + 1 }
    }

    suspend fun addLinkShortCut(shortCutId: Int): Result<Unit> {
        return withContext(Dispatchers.IO) {
            shortCutRepository.addLinkShortCut(shortCutId)
        }
    }

    suspend fun addHistoryShortCut(history: BrowseHistoryEntity): Result<Unit> {
        return withContext(Dispatchers.IO) {
            shortCutRepository.addHistoryShortCut(
                history.title,
                history.url,
                history.icon,
                history.isRootItem()
            )
        }
    }

    suspend fun addFavoriteShortCut(favorites: FavoritesEntity): Result<Unit> {
        return withContext(Dispatchers.IO) {
            shortCutRepository.addFavoriteShortCut(
                favorites.title, favorites.url, favorites.icon, favorites.isRootItem()
            )
        }
    }

}